package com.bookshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.bookshop.entity.request.AlipayForm;
import com.bookshop.entity.response.R;
import com.bookshop.util.OrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author g2l
 * @create 2023-12-28 9:30
 */
@Slf4j
@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private Environment config;

    @PostMapping("/create")
    public R alipay(@RequestBody AlipayForm alipayForm) throws AlipayApiException {

        // 调用支付宝接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        // 配置需要的公共请求参数
        request.setNotifyUrl(config.getProperty("alipay.notify-url"));
        // 支付完成后，我们想让页面跳转回支付成功页面，配置returnUrl
        request.setReturnUrl(config.getProperty("alipay.return-url") + "/" + alipayForm.getOrderNo());

        // 组装当前业务方法的请求参数
        JSONObject bizContent = new JSONObject();

        bizContent.put("out_trade_no", alipayForm.getOrderNo()); // 订单号
        bizContent.put("total_amount", Double.parseDouble(alipayForm.getTotalAmount())); // 单位：元
        String str = "yyyy-MM-dd HH:mm:ss";
        String formatDate = new SimpleDateFormat(str)
                .format(new Date(System.currentTimeMillis() + 1000*60*30));
        bizContent.put("time_expire", formatDate); // 超时时间:30分钟
        bizContent.put("subject", "购物车结算"); // 订单标题
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); // 产品销售码，固定

        request.setBizContent(bizContent.toString()); // 组装参数

        // 执行请求，调用支付宝接口
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        log.info(response.getBody());

        return R.ok().put("html", response.getBody());
    }
}
